package com.mew.sas.quartz;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.entity.back.Online;
import com.mew.common.rest.bo.MewSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

import java.util.List;
import java.util.stream.Collectors;

@EnableScheduling
@Component
public class OnlineQuarze {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private OnlineMapper onlineMapper;
    /**
     * 在线统计
     * 5分钟一次
     */
    @Scheduled(initialDelay =5000, fixedRate = 300000)
    public void push(){
        Online one = onlineMapper.selectOne(new QueryWrapper<Online>().orderByDesc("id").last(" limit 1"));
        Long yyMMddHHmm = Long.parseLong(DateUtil.format(new Date(), "yyMMddHHmm"));
        if (null==one||yyMMddHHmm-one.getId()>=5){
            List<MewSession> values = redisTemplate.opsForHash().values(RedisConstantValue.SESSION_USER)
                    .stream().map(r -> (MewSession) r).filter(s->s.onl == 1).collect(Collectors.toList());
            int leng = values.size();
            Online online = Online.builder().id(yyMMddHHmm).online(leng).build();
            onlineMapper.insert(online);
        }
    }
}
